import 'dart:convert';

import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';

///我的拼团控制器
class MyGroupBuyController extends BaseController with SingleGetTickerProviderMixin {
  late TabController tabController;

  int page = 1;

  dynamic type = null;

  bool hasNextPage = false;

  ///订单列表
  List orderList = [];

  ///拼团详情
  Map groupDetail = {};

  @override
  void onInit() {
    getGroupList();

    tabController = TabController(length: 4, vsync: this);
    tabController.addListener(() {
      if (tabController.indexIsChanging) {
        switch (tabController.index) {
          case 0:
            type = null;
            break;
          case 1:
            type = 0;
            break;
          case 2:
            type = 1;
            break;
          case 3:
            type = 2;
            break;
        }
        getGroupList();
      }
    });
    super.onInit();
  }

  ///获取拼团列表
  getGroupList() {
    Tools.showLoading();
    Network.getGroupList(type, page, 5).then((value) {
      print(value);
      if (page == 1) {
        orderList = value['list'];
      } else {
        orderList.addAll(value['list']);
      }
      hasNextPage = value['hasNextPage'];
      update();
      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
    });
  }

  //获取拼团详情
  getGroupDetail(String orderId) {
    Tools.showLoading();
    Network.getGroupDetail(orderId).then((value) {
      final List headImages = value['imgs'];
      if (headImages.isNotEmpty) {
        headImages.insert(0, value['avatar']);
        value['imgs'] = headImages;
      }
      print(value);
      groupDetail = value;
      logger.i('groupDetail =====$groupDetail');
      update();
      Get.toNamed(Routes.invitedFriends);
      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
    });
  }

  ///邀请好友或查看订单或参团
  void action() {
    switch (groupDetail['bookStatus']) {
      case 0:
        //邀请好友
        print('是不是组团');
        shareMiniProgram();
        break;
      case 1:
        //拼团成功,查看订单
        Get.toNamed(Routes.pendingPayment, arguments: groupDetail['id']);
        break;
      case 2:
        //拼团失败
        Tools.showToast("拼团已失败,请重新发起或参与别的拼团");
        break;
      default:
    }
  }

  Fluwx fluwx = Fluwx();
  // 分享小程序卡片
  void shareMiniProgram() async {
    if (GetPlatform.isIOS || GetPlatform.isAndroid) {
      bool isInstall = await fluwx.isWeChatInstalled;
      if (!isInstall) {
        Tools.showToast('请先安装微信');
        return;
      }

      final data = {
        'sid': AppData.sid, // 确保这个值是有效的
        'bookId': groupDetail['bookId'], // 确保这个值是有效的
      };

      // JSON 序列化和 URL 编码
      String jsonData = jsonEncode(data);

      logger.i('data 字符串 $jsonData');
      var model = WeChatShareMiniProgramModel(
          userName: "gh_ac4763917949", //小程序的原始id,如 gh_d43f693ca31f  gh_09674df0c820  gh_ac4763917949
          webPageUrl: 'https://mv2.bd-ego.com/', //兼容老版本小程序的网页连接
          miniProgramType: WXMiniProgramType.test, //小程序类型，测试版本小程序
          path: "pages/guide/index?type=9&data=$jsonData", //小程序的页面路径支持带?xx=121参数
          title: "还差一人，快来拼团", //分享的标题
          description: "麻烦一起来拼个团", //分享的说明文本
          thumbnail: WeChatImage.asset("assets/images/login_logo.png") //分享的图片
          );

      logger.i('xxxxxx 最后数据 ${model.arguments}');

      fluwx.share(model);
    }
  }

  @override
  void onPageRefresh() async {
    super.onPageRefresh();
    page = 1;
    getGroupList();
    baseRefreshCtr.refreshCompleted(resetFooterState: true);
  }

  @override
  void onPageLoading() async {
    if (hasNextPage == true) {
      super.onPageLoading();
      page += 1;
      getGroupList();
      baseRefreshCtr.loadComplete();
    }
  }

  @override
  void onClose() {
    tabController.dispose();
    super.onClose();
  }
}
